 package com.health.mapp.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.health.commons.MD5Password;
import com.health.commons.PropertiesService;
import com.health.db.model.UserLIST;
import com.health.db.model.UserLISTTemp;
import com.health.db.model.WXUserInfo;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.IWXService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.RegisterByWXReq;
import com.health.mapp.bean.RegisterByWXResp;
import com.health.mapp.bean.WXTokenModel;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import com.wxtools.api.IService;

 /**
 * Created by YYY on 2017/5/20.
 */
public class RegisterForWXImpl implements ActionInterface {

    private IUserLISTService userLISTService;
    private IRongService rongService;
    private ImMsgNoticeService imMsgNoticeService;
    private IWXService wxService;
    private IService mpService;

    @Override
    public Response execute(Header header, Object reqBean) throws Exception {

        RegisterByWXReq req = (RegisterByWXReq) reqBean;
        RegisterByWXResp resp = new RegisterByWXResp();

        String userPhone = req.getUserPhone();
        String password = req.getPassword();
        String wxToken = req.getWxToken();
        String refreshToken = req.getRefreshToken();

        if (StringUtils.isBlank(userPhone) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(wxToken) ||
                StringUtils.isEmpty(refreshToken)) {
            resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
            return resp;
        }

        /**
         * 刷新微信Token
         * */
        WXTokenModel tokenModel = wxService.refreshToken(refreshToken);
        if (null != tokenModel &&
                !StringUtils.isEmpty(tokenModel.getRefresh_token()) &&
                !StringUtils.isEmpty(tokenModel.getAccess_token())) {
            /**
             * 获取微信平台用户信息
             * */
            WXUserInfo wxUserInfo = wxService.getWXUserInfo(tokenModel.getAccess_token(), tokenModel.getOpenid());
            if (null != wxUserInfo) {
                UserLIST user = userLISTService.selectByUserNo(req.getUserPhone());
                UserLISTTemp returnUserBean = new UserLISTTemp();

                if (null == user) {
                    Date now = DateUtils.now();
                    UserLIST userLIST = new UserLIST();

                    //userLIST.setUserAlias("");
                    userLIST.setUserName(wxUserInfo.getNickname());
                    userLIST.setApptoken("");
                    userLIST.setUserNo(req.getUserPhone());
                    userLIST.setPasswordCreateDate(now);
                    userLIST.setLoginDatetime(now);
                    userLIST.setLogoutDatetime(now);
                    userLIST.setPassword(MD5Password.getEncodedPassword_Hex(req.getPassword()));
                    userLIST.setCreateDate(now);
                    userLIST.setUpdateDate(now);
                	userLIST.setRegisterDate(now);

                    userLIST.setTypeid(1);
                    userLIST.setTypeName("用户");
                    userLIST.setIsUsedFlag((short) 1);
                    userLIST.setIconUrl(PropertiesService.getString("iconUrl.userDefaultUrl").trim());
                    //userLIST.setRunstatusid((short) 2);
                    userLIST.setWxopenid(wxUserInfo.getOpenid());

                    userLISTService.insertUser(userLIST);

                    user = userLISTService.selectByUserNo(req.getUserPhone());
                    /**
                     * 在用户数据表里插入新用户信息成功
                     * */
                    if (null != user) {
                        returnUserBean.setUserId(String.valueOf(userLIST.getUserid()));
                        returnUserBean.setUserName(userLIST.getUserName());
                        returnUserBean.setUserPhone(userLIST.getUserNo());
                        returnUserBean.setRegTime(now);
                        returnUserBean.setIcon(userLIST.getIconUrl());

                    } else {
                        resp.setErrorCode(-1);
                        resp.setErrorMsg("用户注册失败");
                        return resp;
                    }

                } else {

                    Short isExportFlag = user.getIsExportFlag();
                    if (null != isExportFlag && 1 == isExportFlag.intValue()) {
                        Date now = DateUtils.now();
                        user.setPassword(MD5Password.getEncodedPassword_Hex(req.getPassword()));
                        user.setPasswordCreateDate(DateUtils.now());
                        user.setWxopenid(wxUserInfo.getOpenid());

                        userLISTService.updatePassword(user);

                        returnUserBean.setUserId(String.valueOf(user.getUserid()));
                        returnUserBean.setUserName(user.getUserName());
                        returnUserBean.setUserPhone(user.getUserNo());
                        returnUserBean.setRegTime(now);
                        returnUserBean.setIcon(user.getIconUrl());

                    } else {
                        resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_NAME_IS_EXISTS);
                        resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_NAME_IS_EXISTS_NOTE);
                        return resp;
                    }

                }

                if (resp.getErrorCode()==ResultCode.OPERATION_SUCCESS)
                {
                    resp.setUser(returnUserBean);
                    resp.setWxToken(tokenModel.getAccess_token());
                    resp.setRefreshToken(tokenModel.getRefresh_token());
                    resp.setRefreshToken(refreshToken);
                }

                return resp;
            } else {
                resp.setErrorCode(-1);
                resp.setErrorMsg("查询微信信息失败");
                return resp;
            }
        } else {
            //微信Autho2.0认证失效

            resp.setErrorCode(-100);
            resp.setErrorMsg("微信认证失效");
            return resp;
        }
    }


    public IUserLISTService getUserLISTService() {
        return userLISTService;
    }

    public void setUserLISTService(IUserLISTService userLISTService) {
        this.userLISTService = userLISTService;
    }

    public IRongService getRongService() {
        return rongService;
    }

    public void setRongService(IRongService rongService) {
        this.rongService = rongService;
    }

    public ImMsgNoticeService getImMsgNoticeService() {
        return imMsgNoticeService;
    }

    public void setImMsgNoticeService(ImMsgNoticeService imMsgNoticeService) {
        this.imMsgNoticeService = imMsgNoticeService;
    }

    public IWXService getWxService() {
        return wxService;
    }

    public void setWxService(IWXService wxService) {
        this.wxService = wxService;
    }

	public IService getMpService() {
		return mpService;
	}

	public void setMpService(IService mpService) {
		this.mpService = mpService;
	}
    
}
